'''
Created on 2021-10-17
@author:xianye
'''

import sdk_umeng
import userinfo
import pandas as pd
import time
import os
import datetime

# 取当前日期
today = datetime.date.today()
# 日期偏移量1天
oneday = datetime.timedelta(days=1)
# 日期偏移量30天
thirtyday = datetime.timedelta(days=30)
# 20200901格式
yesterday = (today - oneday).strftime("%Y%m%d")
# 2021-09-01格式
start_date = (today - thirtyday).strftime("%Y-%m-%d")
end_date = (today - oneday).strftime("%Y-%m-%d")

# 1,获取登录后的API秘钥，后续每个功能调用，都需要这个
auth_token = sdk_umeng.authorize(userinfo.umeng)
# print(auth_token)

# check data,if no,create
try:
    file = os.listdir('./data/')
except:
    os.mkdir('data')

try:
    # 2,获取appkey信息，并遍历出所有的appkey
    apps_list = sdk_umeng.apps(auth_token)
    for appkeys_info in apps_list:
        # print('appkey:',appkeys['appkey'])
        group_list = sdk_umeng.group_list(appkeys_info['appkey'], auth_token, start_date=start_date,
                                          end_date=end_date).json()
        for group_info in group_list:
            # print(group_info)
            daily_data = sdk_umeng.daily_data(appkeys_info['appkey'], auth_token, start_date=start_date,
                                              end_date=end_date, group_id=group_info['group_id']).json()
            # print(daily_data)
            daily_data_df = pd.DataFrame(columns={'date', '数据'})
            daily_data_df['date'] = daily_data['dates']
            daily_data_df['数据'] = daily_data['data']['all']
            # print(daily_data_df.head())
            print(appkeys_info['appkey'],group_info['display_name'])

            daily_data_df.to_excel(
                './data/{}-{}-{}.xlsx'.format(yesterday,appkeys_info['name'], group_info['display_name']), index=False)
            # break
        # break

except Exception as e:
    # Api网关返回的异常
    print(e)
